package com.anonymous.community.hotfix;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

/**
 * 热更新管理器
 * 整合热更新检测、下载、安装功能
 */
public class HotfixManager {
    
    private static final String TAG = "HotfixManager";
    private static final String PREFS_NAME = "hotfix_prefs";
    private static final String KEY_LAST_CHECK_TIME = "last_check_time";
    private static final String KEY_CURRENT_PATCH_VERSION = "current_patch_version";
    private static final String KEY_IGNORE_VERSION = "ignore_version";
    
    private static HotfixManager instance;
    private Context context;
    private HotfixService hotfixService;
    private TinkerManager tinkerManager;
    private PatchDownloader patchDownloader;
    private SharedPreferences prefs;
    private Handler mainHandler;
    
    public interface HotfixListener {
        void onCheckStart();
        void onCheckComplete(boolean hasUpdate, UpdateInfo updateInfo);
        void onDownloadStart();
        void onDownloadProgress(int progress);
        void onDownloadComplete(String filePath);
        void onInstallStart();
        void onInstallComplete(boolean success);
        void onError(String error);
    }
    
    private HotfixManager(Context context) {
        this.context = context.getApplicationContext();
        this.hotfixService = new HotfixService(context);
        this.tinkerManager = TinkerManager.getInstance(context);
        this.patchDownloader = new PatchDownloader(context);
        this.prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        this.mainHandler = new Handler(Looper.getMainLooper());
        
        // 初始化 Tinker
        tinkerManager.initTinker();
    }
    
    public static synchronized HotfixManager getInstance(Context context) {
        if (instance == null) {
            instance = new HotfixManager(context);
        }
        return instance;
    }
    
    /**
     * 检查热更新（无监听器版本，用于静默检查）
     */
    public void checkForUpdates() {
        checkForUpdates(new SilentHotfixListener());
    }
    
    /**
     * 检查热更新
     */
    public void checkForUpdates(HotfixListener listener) {
        if (!HotfixConfig.isHotfixEnabled()) {
            Log.d(TAG, "热更新功能已禁用");
            return;
        }
        
        // 检查网络状态
        if (!isNetworkAvailable()) {
            if (listener != null) {
                mainHandler.post(() -> listener.onError("网络不可用"));
            }
            return;
        }
        
        if (listener != null) {
            mainHandler.post(listener::onCheckStart);
        }
        
        // 异步检查更新
        new Thread(() -> {
            try {
                hotfixService.checkForUpdates(new HotfixService.UpdateCheckListener() {
                    public void onSuccess(UpdateInfo updateInfo) {
                        mainHandler.post(() -> {
                            if (listener != null) {
                                listener.onCheckComplete(updateInfo.isHasUpdate(), updateInfo);
                            }
                            
                            // 如果有更新且符合自动下载条件，开始下载
                            if (updateInfo.isHasUpdate() && shouldAutoDownload(updateInfo)) {
                                downloadAndInstallPatch(updateInfo, listener);
                            }
                        });
                    }
                    
                    public void onError(String error) {
                        mainHandler.post(() -> {
                            if (listener != null) {
                                listener.onError(error);
                            }
                        });
                    }
                });
                
                // 更新最后检查时间
                updateLastCheckTime();
                
            } catch (Exception e) {
                Log.e(TAG, "检查更新异常", e);
                mainHandler.post(() -> {
                    if (listener != null) {
                        listener.onError("检查更新失败: " + e.getMessage());
                    }
                });
            }
        }).start();
    }
    
    /**
     * 下载并安装补丁
     */
    public void downloadAndInstallPatch(UpdateInfo updateInfo, HotfixListener listener) {
        if (updateInfo == null || !updateInfo.isHasUpdate()) {
            if (listener != null) {
                listener.onError("无效的更新信息");
            }
            return;
        }
        
        // 检查是否忽略此版本
        if (isVersionIgnored(updateInfo.getPatchVersion())) {
            Log.d(TAG, "用户已忽略版本: " + updateInfo.getPatchVersion());
            return;
        }
        
        if (listener != null) {
            listener.onDownloadStart();
        }
        
        // 下载补丁
        patchDownloader.downloadPatch(updateInfo, new PatchDownloader.DownloadListener() {
            public void onStart() {
                Log.d(TAG, "开始下载补丁");
            }
            
            public void onProgress(int progress) {
                if (listener != null) {
                    mainHandler.post(() -> listener.onDownloadProgress(progress));
                }
            }
            
            public void onSuccess(String filePath) {
                mainHandler.post(() -> {
                    if (listener != null) {
                        listener.onDownloadComplete(filePath);
                        listener.onInstallStart();
                    }
                    
                    // 安装补丁
                    installPatch(filePath, updateInfo, listener);
                });
            }
            
            public void onError(String error) {
                mainHandler.post(() -> {
                    if (listener != null) {
                        listener.onError("下载失败: " + error);
                    }
                });
            }
        });
    }
    
    /**
     * 安装补丁
     */
    private void installPatch(String patchPath, UpdateInfo updateInfo, HotfixListener listener) {
        new Thread(() -> {
            try {
                boolean success = tinkerManager.installPatch(patchPath);
                
                mainHandler.post(() -> {
                    if (listener != null) {
                        listener.onInstallComplete(success);
                    }
                    
                    if (success) {
                        // 保存当前补丁版本
                        saveCurrentPatchVersion(updateInfo.getPatchVersion());
                        Log.i(TAG, "补丁安装成功，版本: " + updateInfo.getPatchVersion());
                    } else {
                        Log.e(TAG, "补丁安装失败");
                    }
                });
                
            } catch (Exception e) {
                Log.e(TAG, "安装补丁异常", e);
                mainHandler.post(() -> {
                    if (listener != null) {
                        listener.onError("安装失败: " + e.getMessage());
                    }
                });
            }
        }).start();
    }
    
    /**
     * 是否应该自动下载
     */
    private boolean shouldAutoDownload(UpdateInfo updateInfo) {
        // 强制更新
        if (updateInfo.isForceUpdate()) {
            return true;
        }
        
        // 检查WiFi自动下载设置
        if (HotfixConfig.isAutoDownloadOnWifi() && isWifiConnected()) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 检查网络是否可用
     */
    private boolean isNetworkAvailable() {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isConnected();
        } catch (Exception e) {
            Log.e(TAG, "检查网络状态失败", e);
            return false;
        }
    }
    
    /**
     * 检查是否连接WiFi
     */
    private boolean isWifiConnected() {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
        } catch (Exception e) {
            Log.e(TAG, "检查WiFi状态失败", e);
            return false;
        }
    }
    
    /**
     * 更新最后检查时间
     */
    private void updateLastCheckTime() {
        prefs.edit().putLong(KEY_LAST_CHECK_TIME, System.currentTimeMillis()).apply();
    }
    
    /**
     * 获取最后检查时间
     */
    public long getLastCheckTime() {
        return prefs.getLong(KEY_LAST_CHECK_TIME, 0);
    }
    
    /**
     * 保存当前补丁版本
     */
    private void saveCurrentPatchVersion(String version) {
        prefs.edit().putString(KEY_CURRENT_PATCH_VERSION, version).apply();
    }
    
    /**
     * 获取当前补丁版本
     */
    public String getCurrentPatchVersion() {
        return prefs.getString(KEY_CURRENT_PATCH_VERSION, null);
    }
    
    /**
     * 忽略版本
     */
    public void ignoreVersion(String version) {
        prefs.edit().putString(KEY_IGNORE_VERSION, version).apply();
    }
    
    /**
     * 检查版本是否被忽略
     */
    private boolean isVersionIgnored(String version) {
        String ignoredVersion = prefs.getString(KEY_IGNORE_VERSION, null);
        return version != null && version.equals(ignoredVersion);
    }
    
    /**
     * 清理补丁
     */
    public void cleanPatch() {
        tinkerManager.cleanPatch();
        patchDownloader.cleanOldPatches();
        prefs.edit().remove(KEY_CURRENT_PATCH_VERSION).apply();
    }
    
    /**
     * 获取Tinker状态
     */
    public String getTinkerStatus() {
        return tinkerManager.getTinkerStatus();
    }
    
    /**
     * 重启应用
     */
    public void restartApp() {
        tinkerManager.restartApp();
    }
    
    /**
     * 静默热更新监听器
     * 用于后台静默检查和安装更新，不显示UI提示
     */
    private static class SilentHotfixListener implements HotfixListener {
        private static final String TAG = "SilentHotfixListener";
        
        @Override
        public void onCheckStart() {
            Log.d(TAG, "开始静默检查更新");
        }
        
        @Override
        public void onCheckComplete(boolean hasUpdate, UpdateInfo updateInfo) {
            if (hasUpdate) {
                Log.d(TAG, "发现新版本: " + updateInfo.getPatchVersion());
            } else {
                Log.d(TAG, "当前已是最新版本");
            }
        }
        
        @Override
        public void onDownloadStart() {
            Log.d(TAG, "开始静默下载补丁");
        }
        
        @Override
        public void onDownloadProgress(int progress) {
            Log.d(TAG, "下载进度: " + progress + "%");
        }
        
        @Override
        public void onDownloadComplete(String filePath) {
            Log.d(TAG, "补丁下载完成: " + filePath);
        }
        
        @Override
        public void onInstallStart() {
            Log.d(TAG, "开始静默安装补丁");
        }
        
        @Override
        public void onInstallComplete(boolean success) {
            if (success) {
                Log.d(TAG, "补丁安装成功，下次启动生效");
            } else {
                Log.e(TAG, "补丁安装失败");
            }
        }
        
        @Override
        public void onError(String error) {
            Log.e(TAG, "静默更新出错: " + error);
        }
    }
}